package com.example.service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private MyService.MyBinder myBinder;
    private MyServiceConnection connection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        Button btnBind = findViewById(R.id.btn_bind);
        Button btnCall = findViewById(R.id.btn_call);
        Button btnUnbind = findViewById(R.id.btn_unbind);

        btnBind.setOnClickListener(this);
        btnCall.setOnClickListener(this);
        btnUnbind.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_bind:
                if (connection == null) {
                    connection = new MyServiceConnection();
                }
                Intent intent = new Intent(MainActivity.this, MyService.class);
                bindService(intent, connection, BIND_AUTO_CREATE); //绑定服务
                break;
            case R.id.btn_call:
                myBinder.callMethodInService(); //调用服务中的方法
                break;
            case R.id.btn_unbind:
                if (connection != null) {
                    unbindService(connection);  //解绑服务
                    connection = null;
                }
                break;
        }
    }

    /**
     * 创建连接服务的ServiceConnection类
     */
    private class MyServiceConnection implements ServiceConnection {

        // 当成功绑定服务时调用,该方法获取 MyService中的 Ibinder对象
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyService.MyBinder) service;
            Log.i("MainActivity", "服务绑定成功，内存地址：" + myBinder.toString());
        }

        // 当服务失去连接时调用
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}